﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using Ewts.Code;
using DataLib.Accounts.Bus;
using DataLib.Common;
//using Excel;
using System.Text;
using System.IO;


namespace EWMSWeb.Query
{
    public partial class StorageItems : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                if (Session["UserInfo"] == null)
                {

                    Response.Redirect("/Accounts/Login.aspx");
                    return;
                }

                //参数为LoadNumID
                ListItem item = new ListItem();
                item.Text = "--请选择--";
                item.Value = "";
                DataLib.BLL.City bllLib = new DataLib.BLL.City();

                // 处理地
                dropGcity.DataSource = bllLib.GetList(" flag1 ='02'");
                dropGcity.DataTextField = "cityname";
                dropGcity.DataValueField = "cityname";
                dropGcity.DataBind();
                dropGcity.Items.Insert(0, item);


                // 归属地
                dropBcity.DataSource = bllLib.GetList(" flag1 ='01'");
                dropBcity.DataTextField = "cityname";
                dropBcity.DataValueField = "cityname";
                dropBcity.DataBind();
                dropBcity.Items.Insert(0, item);


                User curUser = new DataLib.Accounts.Bus.User();
                curUser = (User)Session["UserInfo"];
                if (curUser.UserType != "AD")
                {
                    dropGcity.SelectedValue = curUser.CompanyCity;
                    dropGcity.Enabled = false;
                }
                else
                {
                    dropGcity.SelectedValue = "全部";
                }
            }


        }


        //public void bindData()
        //{
        //    string bcity = dropBcity.SelectedValue;
        //    string gcity = dropGcity.SelectedValue;
        //    string enddate = txtDate.Text;

         
        //    string error = ConfirmDate();
        //    if (error != "")
        //    {
        //        DataLib.Common.MessageBox.Show(Page, error);
        //    }
        //    else
        //    {
        //        //2015年4月16日 21:52:04  FIFA 把这部分放到移动到这个位置,原来在else外面
        //        DateTime etime = new DateTime();
        //        etime = DateTime.Parse(enddate);
        //        etime = etime.AddHours(double.Parse(txtHour.Text.Trim()));
        //        etime = etime.AddMinutes(double.Parse(txtMinute.Text.Trim()));
        //        etime = etime.AddSeconds(double.Parse(txtSecond.Text.Trim()));
        //        enddate = etime.ToString();
        //        /////////////////////////////////////////////////////////////////////

        //        DataTable dt = new DataTable();
        //        dt = new DataLib.BLL.StorageData().StorageItemsQuery(enddate, bcity, gcity);
        //        rept.DataSource = dt;
        //        rept.DataBind();
        //    }
         
        //}

        private DataTable GetDT()
        {

            string bcity = dropBcity.SelectedValue;
            string gcity = dropGcity.SelectedValue;
            string enddate = txtDate.Text;


            string error = ConfirmDate();
            if (error != "")
            {
                DataLib.Common.MessageBox.Show(Page, error);
                return null;
            }
            else
            {
                //2015年4月16日 21:52:04  FIFA 把这部分放到移动到这个位置,原来在else外面
                DateTime etime = new DateTime();
                etime = DateTime.Parse(enddate);
                etime = etime.AddHours(double.Parse(txtHour.Text.Trim()));
                etime = etime.AddMinutes(double.Parse(txtMinute.Text.Trim()));
                etime = etime.AddSeconds(double.Parse(txtSecond.Text.Trim()));
                enddate = etime.ToString();
                /////////////////////////////////////////////////////////////////////

                DataTable dt = new DataTable();
           
                dt = new DataLib.BLL.StorageData().GetStorageItemsQuery(enddate, bcity, gcity);
                return dt;
            }
        }

        
        /// <summary>
        /// 验证日期
        /// </summary>
        /// <returns>提示</returns>
        protected string ConfirmDate()
        {
            string strErr = "";
            if (!PageValidate.IsDateTime(txtDate.Text))
            {
                strErr += "请输入正确的查询日期 \\n";
            }
            if (!PageValidate.IsNumber(txtHour.Text))
            {
                strErr += "请输入正确的小时数字\\n";
            }
            if (!PageValidate.IsNumber(txtMinute.Text))
            {
                strErr += "请输入正确的分钟数字\\n";
            }
            if (!PageValidate.IsNumber(txtSecond.Text))
            {
                strErr += "请输入正确的秒数\\n";
            }
            return strErr;
        }

        protected void btnExport_Click(object sender, EventArgs e)
        {
            System.Data.DataTable dt = GetDT();
            try
            {
                StringWriter swCSV = new StringWriter();
                //列名
                swCSV.WriteLine(@"序号,归属地,处理地,项目编码,项目名称,Load,客户,客户简称,财务编码,物品编码,物品名称,毛重,皮1,皮2,净重,废物编码	,废物名称,箱号,条码,入库日期,库存类型,结算月,锁定状态");

                //遍历datatable导出数据
                foreach (DataRow drTemp in dt.Rows)
                {
                    StringBuilder sbText = new StringBuilder();
                    sbText = AppendCSVFields(sbText, drTemp["rowno"].ToString());
                    sbText = AppendCSVFields(sbText, drTemp["bcity"].ToString());
                    sbText = AppendCSVFields(sbText, drTemp["gcity"].ToString());
                    sbText = AppendCSVFields(sbText, drTemp["projectcode"].ToString());
                    sbText = AppendCSVFields(sbText, drTemp["projectname"].ToString());
                    sbText = AppendCSVFields(sbText, drTemp["load"].ToString());
                    sbText = AppendCSVFields(sbText, drTemp["cumname"].ToString());
                    sbText = AppendCSVFields(sbText, drTemp["cumshortname"].ToString());
                    sbText = AppendCSVFields(sbText, drTemp["bussCode"].ToString());
                    sbText = AppendCSVFields(sbText, drTemp["goodscode"].ToString());
                    sbText = AppendCSVFields(sbText, drTemp["goodsname"].ToString());
                    sbText = AppendCSVFields(sbText, drTemp["gwt"].ToString());
                    sbText = AppendCSVFields(sbText, drTemp["tare1"].ToString());
                    sbText = AppendCSVFields(sbText, drTemp["tare2"].ToString());
                    sbText = AppendCSVFields(sbText, drTemp["nwt"].ToString());
                    sbText = AppendCSVFields(sbText, drTemp["rubcode"].ToString());
                    sbText = AppendCSVFields(sbText, drTemp["rubname"].ToString());
                    sbText = AppendCSVFields(sbText, drTemp["boxno"].ToString());
                    sbText = AppendCSVFields(sbText, drTemp["barcodevalue"].ToString());
                    sbText = AppendCSVFields(sbText, drTemp["insdate"].ToString());
                    sbText = AppendCSVFields(sbText, drTemp["SType"].ToString());
                    sbText = AppendCSVFields(sbText, drTemp["clearingmonth"].ToString());
                    sbText = AppendCSVFields(sbText, drTemp["lockstatus"].ToString());
                    //去掉尾部的逗号
                    sbText.Remove(sbText.Length - 1, 1);

                    //写datatable的一行
                    swCSV.WriteLine(sbText.ToString());
                }
                //下载文件
                string filename = "Storage_" + DateTime.Now.Year.ToString() + "_" + DateTime.Now.Month.ToString() + "_" + DateTime.Now.Day + ".csv"; 
                DownloadFile(Response, swCSV.GetStringBuilder(), filename);

                swCSV.Close();
                Response.End();

            }
            catch (Exception ex)
            {
                throw ex;
            }
         
        }

        //protected void exportOld(DataTable dt)
        //{
        //    DataTable[] exportData = { dt };

        //    //只导出第一张表，数据量超大会自动分页。
        //    string tempFilePath = Server.MapPath("/upload/");
        //    string fileName = "库存明细_" + DateTime.Now.Ticks.ToString();
        //    string excelVersion = "";
        //    string ContentType = "";
        //    //判断Excel版本

        //    excelVersion = ExcelVersion.Excel12;
        //    fileName = fileName + ".xlsx";
        //    ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";

        //    //关键语句：调用ExcelFile组件执行导出操作。
        //    ExcelFile.SetData(exportData[0], tempFilePath + fileName, excelVersion, HDRType.Yes);


        //    //写文件到客户端
        //    Session["fileName"] = fileName;
        //    Session["filePath"] = tempFilePath + fileName;
        //    Session["ContentType"] = ContentType;
        //    //防止页面不刷新，从客户端调用下载文件。
        //    string urlDownload = Request.Url.OriginalString.Replace("StorageItems.aspx", "Excel.aspx");
        //    urlDownload = urlDownload.Replace("StorageItems.aspx", "Excel.aspx");

        //    ClientScript.RegisterStartupScript(this.GetType(), "clientScipt",
        //        "window.open('" + urlDownload + "','','width=1,height=1,toolbar=no,location=no,menubar=no');", true);
        //}

      

        /// <summary>
        /// csv添加逗号 用来区分列
        /// </summary>
        /// <param name="argFields">字段</param>
        /// <returns>添加后内容</returns>
        private StringBuilder AppendCSVFields(StringBuilder argSource, string argFields)
        {
            return argSource.Append(argFields.Replace(",", " ").Trim()).Append(",");
        }


        /// <summary>
        /// 弹出下载框
        /// </summary>
        /// <param name="argResp">弹出页面</param>
        /// <param name="argFileStream">文件流</param>
        /// <param name="strFileName">文件名</param>
        public static void DownloadFile(HttpResponse argResp, StringBuilder argFileStream, string strFileName)
        {
            try
            {
                string strResHeader = "attachment; filename=" + Guid.NewGuid().ToString() + ".csv";
                if (!string.IsNullOrEmpty(strFileName))
                {
                    strResHeader = "attachment; filename=" + strFileName;
                }
                argResp.AppendHeader("Content-Disposition", strResHeader);//attachment说明以附件下载，inline说明在线打开
                argResp.ContentType = "application/ms-excel";
                argResp.ContentEncoding = Encoding.GetEncoding("GB2312"); // Encoding.UTF8;//
                argResp.Write(argFileStream);

            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        protected void btnQuery_Click(object sender, EventArgs e)
        {
            bindPageData(0);
        }

        protected void AspNetPager1_PageChanged(object sender, EventArgs e)
        {
            bindPageData(page1.StartRecordIndex);
        }

        protected void bindPageData(int current)
        {
            string bcity = dropBcity.SelectedValue;
            string gcity = dropGcity.SelectedValue;
            string enddate = txtDate.Text;


            DateTime etime = new DateTime();
            etime = DateTime.Parse(enddate);
            etime = etime.AddHours(double.Parse(txtHour.Text.Trim()));
            etime = etime.AddMinutes(double.Parse(txtMinute.Text.Trim()));
            etime = etime.AddSeconds(double.Parse(txtSecond.Text.Trim()));
            enddate = etime.ToString();
            DataLib.BLL.StorageData bll = new DataLib.BLL.StorageData();
            DataTable dt = new DataTable();
            int totalRecord;
            dt = bll.StorageItemsQueryPage(enddate, bcity, gcity, current, 25, out totalRecord);
            page1.RecordCount = totalRecord;
            rept.DataSource = dt;
            rept.DataBind();
        }
    }
}